package handler

import (
	"net/http"
	"ywebgo/context"
)

type MapHandler struct {
	HandlerMaps map[string]HandleFunc
}

func (h *MapHandler) ObtainKey(method string, pattern string) string {
	return method + "#" + pattern
}

func (h *MapHandler) Enroll(method string, pattern string, handleFunc HandleFunc) {
	key := h.ObtainKey(method, pattern)
	h.HandlerMaps[key] = handleFunc
}

func (h *MapHandler) Handle(w http.ResponseWriter, r *http.Request) {
	key := h.ObtainKey(r.Method, r.URL.Path)
	if handler, ok := h.HandlerMaps[key]; ok {
		handler(context.NewContext(w, r))
	} else {
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte("Not Found"))
	}
}

func NewMapHandler() *MapHandler {
	return &MapHandler{HandlerMaps: make(map[string]HandleFunc)}
}
